import 'dart:async';
import 'dart:convert';

import 'package:collection/collection.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:go_router/go_router.dart';
import 'package:leader_doctor_flutter/common/data/app.dart';
import 'package:leader_doctor_flutter/common/extension/my_extension.dart';
import 'package:leader_doctor_flutter/common/utils/consultation_utils.dart';
import 'package:leader_doctor_flutter/common/utils/image_utils.dart';
import 'package:leader_doctor_flutter/common/utils/string_utils.dart';
import 'package:leader_doctor_flutter/common/utils/user_utils.dart';
import 'package:leader_doctor_flutter/plugins/plugins_messages.g.dart';
import '../../../common/http/api.dart';
import '../../../common/http/http_client.dart';
import '../../../common/utils/date_utils.dart';
import '../../../common/widget/comm_widget.dart';
import '../../../model/consult.dart';
import '../../../router/router.dart';
import '../../../styles/colors.dart';
import '../../wallet/model/dict.dart';

/// @Author lixiaobin
/// @Date 2024/2/22
/// @Description 咨询详情
class ConsultationDetailPage extends StatefulWidget {
  final String? consultId;
  final ConsultModel? consultModel;

  const ConsultationDetailPage({super.key, required this.consultId, required this.consultModel});

  @override
  State<ConsultationDetailPage> createState() => _ConsultationDetailPageState();
}

class _ConsultationDetailPageState extends State<ConsultationDetailPage> with WidgetsBindingObserver {
  ConsultModel? _consultModel;
  Timer? _timer;
  String _timeRemaining = '00:00:00';
  String? _phoneStr;
  var _imgArr = <String>[];
  int status = 0;

  @override
  void initState() {
    super.initState();
    _getConsultData();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) {
      _getConsultData();
    }
  }

  void _getConsultData() {
    if (widget.consultModel != null) {
      _setConsultModel(widget.consultModel);
    } else {
      _findConsultDetail();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        resizeToAvoidBottomInset: false,
        appBar: CommWidget.getCommAppbar(context),
        backgroundColor: ColorRes.white,
        body: _consultModel == null
            ? CommWidget.buildEmptyView(tipStr: status == 0 ? '数据正在加载中请稍后' : '暂无数据')
            : Column(
                children: [
                  Expanded(
                      child: SingleChildScrollView(
                          child: Column(
                    children: [
                      _buildHeadView(),
                      _buildContentView(),
                      _buildFootView(),
                    ],
                  ))),
                  _buildFootViewBtn()
                ],
              ));
  }

  Container _buildFootViewBtn() {
    var isNoConsultation = _isNoConsultation() ||
        _isProceedConsultation() && ConsultationUtils.isPhoneConsult(_consultModel?.type) ||
        _isProceedConsultation() && ConsultationUtils.isVideoConsult(_consultModel?.type) ||
        _isProceedConsultation() && ConsultationUtils.isImageTextConsult(_consultModel?.type);
    return Container(
        padding: isNoConsultation ? EdgeInsets.only(left: 12.w, right: 12.w, top: 17.w) : EdgeInsets.zero,
        decoration: BoxDecoration(
          color: Colors.white,
          boxShadow: [
            BoxShadow(
              color: Colors.grey.withOpacity(0.1),
              spreadRadius: 1,
              blurRadius: 5,
              offset: const Offset(0, 1),
            ),
          ],
        ),
        child: Column(children: [
          _buildFootBtn(
            '暂不接诊',
            '确认接诊',
            _isNoConsultation(),
            () => _getRefuseList(),
            () => _handlerConsultation(),
          ),
          _buildFootBtn(
              '去会话',
              '拨号呼叫',
              _isProceedConsultation() && ConsultationUtils.isPhoneConsult(_consultModel?.type),
              () => _startImageTextConsultation(),
              () => _phoneCall()),
          _buildFootBtn(
              '去会话',
              '视频通话',
              _isProceedConsultation() && ConsultationUtils.isVideoConsult(_consultModel?.type),
              () => _startImageTextConsultation(),
              () => _videoCall()),
          _buildFootBtn(
              null,
              '继续咨询',
              _isProceedConsultation() && ConsultationUtils.isImageTextConsult(_consultModel?.type),
              () {},
              () => _startImageTextConsultation()),
        ]));
  }

  /// 咨询详情 head view 展示
  Widget _buildHeadView() {
    if (_isNoConsultation() || _isProceedConsultation()) {
      return _buildHeadView1();
    } else if (_isCoverConsultation()) {
      return _buildHeadView2();
    }
    return _buildHeadView1();
  }

  Widget _buildHeadView1() {
    return Container(
      height: 32.w,
      padding: EdgeInsets.only(left: 12.w, right: 12.w),
      color: ColorRes.colore6e6ff,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          ImageLoader.loadAsset('icon_consult_time.webp', 15.w),
          SizedBox(width: 5.w),
          Text(
            _isNoConsultation() ? '待接诊' : '咨询中',
            style: TextStyle(
              color: ColorRes.color00e3bd,
              fontSize: 14.sp,
            ),
          ),
          Expanded(
              child: Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              Text(
                '剩余时长：',
                style: TextStyle(
                  color: ColorRes.color666666,
                  fontSize: 14.sp,
                ),
              ),
              Text(
                _timeRemaining,
                style: TextStyle(
                  color: ColorRes.color00e3bd,
                  fontSize: 14.sp,
                ),
              ),
              SizedBox(width: 8.w),
              Text(
                _isNoConsultation() ? '请尽快接诊!' : '',
                style: TextStyle(
                  color: ColorRes.color666666,
                  fontSize: 14.sp,
                ),
              ),
            ],
          ))
        ],
      ),
    );
  }

  Widget _buildHeadView2() {
    return Container(
        height: 57.w,
        color: ColorRes.colore6e6ff,
        child: Row(
          children: [
            SizedBox(width: 12.w),
            ImageLoader.loadAsset(_getStatusImage(), 0, size: Size(45.w, 35.w)),
            SizedBox(width: 10.w),
            Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Visibility(
                    visible: _getRefundStr() != null,
                    child: Text(
                      _getRefundStr() ?? '',
                      style: TextStyle(
                        color: ColorRes.color00e3bd,
                        fontSize: 14.sp,
                      ),
                    )),
                Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Text(
                      _getReasonTitleStr(),
                      style: TextStyle(
                        color: ColorRes.color666666,
                        fontSize: 14.sp,
                      ),
                    ),
                    Text(
                      _getReasonStr(),
                      style: TextStyle(
                        color: ColorRes.color333333,
                        fontSize: 14.sp,
                      ),
                    )
                  ],
                ),
              ],
            ),
          ],
        ));
  }

  ///
  Widget _buildContentView() {
    return Column(
      children: [
        Container(
          padding: EdgeInsets.only(left: 12.w, right: 12.w),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              SizedBox(height: 15.w),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    '就诊人:',
                    style: TextStyle(
                      color: ColorRes.color999999,
                      fontSize: 15.sp,
                    ),
                  ),
                  SizedBox(width: 10.w),
                  Text(
                    ConsultModel.getPatientName(_consultModel),
                    style: TextStyle(
                      color: ColorRes.color333333,
                      fontSize: 15.sp,
                    ),
                  ),
                  SizedBox(width: 10.w),
                  Text(
                    UserUtils.getSexAndAge(_consultModel?.patientSex, _consultModel?.patientAge),
                    style: TextStyle(
                      color: ColorRes.color333333,
                      fontSize: 15.sp,
                    ),
                  ),
                  Expanded(
                      child: Text(
                    ConsultationUtils.getType(_consultModel?.type),
                    textAlign: TextAlign.right,
                    style: TextStyle(
                      color: ColorRes.colorffb50c,
                      fontSize: 12.sp,
                    ),
                  ))
                ],
              ),
              SizedBox(height: 15.w),
              CommWidget.buildLine(),
              SizedBox(height: 17.w),
              Row(
                children: [
                  ImageLoader.loadAsset('icon_consult_info_chief.webp', 20.w),
                  SizedBox(width: 5.w),
                  Text(
                    '主诉',
                    style: TextStyle(
                      color: ColorRes.color333333,
                      fontWeight: FontWeight.bold,
                      fontSize: 15.sp,
                    ),
                  ),
                ],
              ),
              SizedBox(height: 14.w),
              Text(
                _consultModel?.illDescribe ?? '',
                style: TextStyle(
                  color: ColorRes.color666666,
                  fontSize: 15.sp,
                ),
              ),
              SizedBox(height: 15.w),
              Row(
                children: [
                  ImageLoader.loadAsset('icon_consult_info_medical.webp', 20.w),
                  SizedBox(width: 5.w),
                  Text(
                    '病历',
                    style: TextStyle(
                      color: ColorRes.color333333,
                      fontWeight: FontWeight.bold,
                      fontSize: 15.sp,
                    ),
                  ),
                  SizedBox(width: 5.w),
                  Text(
                    '(点击放大查看原图)',
                    style: TextStyle(
                      color: ColorRes.color999999,
                      fontSize: 12.sp,
                    ),
                  ),
                ],
              ),
              Container(
                height: 65.w,
                margin: EdgeInsets.only(top: 13.w),
                alignment: Alignment.center,
                child: _imgArr.isNotEmpty
                    ? GridView.builder(
                        itemCount: _imgArr.length,
                        shrinkWrap: true,
                        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                            crossAxisCount: 5, crossAxisSpacing: 10.w, childAspectRatio: 1.0),
                        itemBuilder: (c, i) {
                          return GestureDetector(
                              onTap: () {
                                context.push(PageUrl.browseImage, extra: {'imgArr': _imgArr, 'selectIndex': i});
                              },
                              child: ImageLoader.loadImage(_imgArr[i], fit: BoxFit.fill));
                        })
                    : Text(
                        '患者未上传',
                        style: TextStyle(
                          color: ColorRes.color999999,
                          fontSize: 12.sp,
                        ),
                      ),
              ),
            ],
          ),
        ),
        Container(
          height: 40.w,
          padding: EdgeInsets.only(left: 12.w, right: 12.w),
          margin: EdgeInsets.only(top: 45.w),
          color: ColorRes.colorf5f5f5,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                '咨询费用',
                style: TextStyle(
                  color: ColorRes.color999999,
                  fontSize: 14.sp,
                ),
              ),
              Text(
                '￥${StringUtils.formatNumber(_consultModel?.price)}',
                style: TextStyle(
                  color: ColorRes.color333333,
                  fontSize: 14.sp,
                ),
              )
            ],
          ),
        ),
        CommWidget.buildLine(),
        Container(
          height: 40.w,
          color: ColorRes.colorf5f5f5,
          padding: EdgeInsets.only(left: 12.w, right: 12.w),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                '问诊时间',
                style: TextStyle(
                  color: ColorRes.color999999,
                  fontSize: 14.sp,
                ),
              ),
              Text(
                _consultModel?.orderTime ?? '',
                style: TextStyle(
                  color: ColorRes.color333333,
                  fontSize: 14.sp,
                ),
              )
            ],
          ),
        ),
        Visibility(
            visible: _isCoverConsultation(),
            child: Column(
              children: [
                CommWidget.buildLine(),
                Container(
                  height: 40.w,
                  color: ColorRes.colorf5f5f5,
                  padding: EdgeInsets.only(left: 12.w, right: 12.w),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        '结束时间',
                        style: TextStyle(
                          color: ColorRes.color999999,
                          fontSize: 14.sp,
                        ),
                      ),
                      Text(
                        _consultModel?.endTime ?? '',
                        style: TextStyle(
                          color: ColorRes.color333333,
                          fontSize: 14.sp,
                        ),
                      )
                    ],
                  ),
                ),
                SizedBox(height: 50.w),
                Visibility(
                    visible: !_isShowMsgHistory(),
                    child: GestureDetector(
                      behavior: HitTestBehavior.opaque,
                      onTap: () {
                        NativeInterface().openNativePage('msg_history', jsonEncode(_consultModel?.toJson()));
                      },
                      child: Container(
                        height: 40.w,
                        width: double.infinity,
                        margin: EdgeInsets.only(left: 12.w, right: 12.w),
                        alignment: Alignment.center,
                        decoration:
                            BoxDecoration(color: ColorRes.colorf5f5f5, borderRadius: BorderRadius.circular(20.w)),
                        child: Text(
                          '查看聊天记录',
                          style: TextStyle(color: ColorRes.color666666, fontSize: 15.sp),
                        ),
                      ),
                    ))
              ],
            ))
      ],
    );
  }

  ///
  Widget _buildFootView() {
    var user = App.instance.userInfo;
    return Container(
      padding: EdgeInsets.only(left: 12.w, right: 12.w, top: 17.w),
      child: Column(
        children: [
          Visibility(
              visible: _getAlertMsg() != null,
              child: Text(
                _getAlertMsg() ?? '',
                style: TextStyle(
                  color: ColorRes.color6198f7,
                  fontSize: 13.sp,
                ),
              )),
          SizedBox(height: 15.w),
          Visibility(
            visible: _isShowCallView(),
            child: Container(
                height: 150.w,
                child: Stack(
                  alignment: Alignment.center,
                  children: [
                    Positioned(
                        left: 0.w,
                        right: 0.w,
                        child: Row(
                          children: [
                            Expanded(
                                child: Column(
                              children: [
                                ClipRRect(
                                    borderRadius: BorderRadius.circular(27.w),
                                    child: ImageLoader.loadSelfAvatar(user?.headIcon,
                                        sex: user?.sex, size: Size(54.w, 54.w))),
                                SizedBox(height: 20.w),
                                Text(
                                  _consultModel?.doctorName ?? '',
                                  style: TextStyle(
                                      color: ColorRes.color333333, fontWeight: FontWeight.bold, fontSize: 15.sp),
                                ),
                                SizedBox(height: 5.w),
                                Visibility(
                                    visible: ConsultationUtils.isPhoneConsult(_consultModel?.type),
                                    child: GestureDetector(
                                        behavior: HitTestBehavior.opaque,
                                        onTap: () {
                                          _buildEditPhoneNumberDialog();
                                        },
                                        child: Row(
                                          children: [
                                            Text(
                                              _phoneStr ?? _consultModel?.doctorPhone ?? '',
                                              style: TextStyle(
                                                  color: ColorRes.color999999,
                                                  fontWeight: FontWeight.bold,
                                                  fontSize: 15.sp),
                                            ),
                                            SizedBox(width: 5.w),
                                            ImageLoader.loadAsset('icon_consultation_v_p_edit.png', 20.w),
                                          ],
                                        )))
                              ],
                            )),
                            SizedBox(width: 100.w),
                            Expanded(
                                child: Column(
                              children: [
                                ClipRRect(
                                    borderRadius: BorderRadius.circular(27.w),
                                    child: ImageLoader.loadPatientAvatar(_consultModel?.patientHeadIcon,
                                        size: Size(54.w, 54.w))),
                                SizedBox(height: 20.w),
                                Text(
                                  '患者：${ConsultModel.getPatientName(_consultModel)}',
                                  style: TextStyle(
                                      color: ColorRes.color333333, fontWeight: FontWeight.bold, fontSize: 15.sp),
                                ),
                                SizedBox(height: 5.w),
                                Visibility(
                                    visible: ConsultationUtils.isPhoneConsult(_consultModel?.type),
                                    child: Text(
                                      _consultModel?.patientPhone ?? '',
                                      style: TextStyle(
                                          color: ColorRes.color999999, fontWeight: FontWeight.bold, fontSize: 15.sp),
                                    ))
                              ],
                            ))
                          ],
                        )),
                    Positioned(
                        left: 0.w,
                        right: 0.w,
                        top: 20.w,
                        child: Container(
                            margin: EdgeInsets.only(top: 10.w, left: 10.w),
                            alignment: Alignment.center,
                            width: 150.w,
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                ImageLoader.loadAsset('icon_line_dashes.png', 0, size: Size(60.w, 2.w)),
                                ImageLoader.loadAsset(
                                    ConsultationUtils.isPhoneConsult(_consultModel?.type)
                                        ? 'icon_consultation_phone.webp'
                                        : 'icon_consultation_video.webp',
                                    35.w),
                                ImageLoader.loadAsset('icon_line_dashes.png', 0, size: Size(60.w, 2.w)),
                              ],
                            ))),
                  ],
                )),
          ),
          // _buildFootBtn(
          //   '暂不接诊',
          //   '确认接诊',
          //   _isNoConsultation(),
          //   () => _getRefuseList(),
          //   () => _handlerConsultation(),
          // ),
          // _buildFootBtn(
          //     '去会话',
          //     '拨号呼叫',
          //     _isProceedConsultation() && ConsultationUtils.isPhoneConsult(_consultModel?.type),
          //     () => _startImageTextConsultation(),
          //     () => _phoneCall()),
          // _buildFootBtn(
          //     '去会话',
          //     '视频通话',
          //     _isProceedConsultation() && ConsultationUtils.isVideoConsult(_consultModel?.type),
          //     () => _startImageTextConsultation(),
          //     () => _videoCall()),
          // _buildFootBtn(
          //     null,
          //     '继续咨询',
          //     _isProceedConsultation() && ConsultationUtils.isImageTextConsult(_consultModel?.type),
          //     () => _startImageTextConsultation(),
          //     () {}),
        ],
      ),
    );
  }

  Visibility _buildFootBtn(String? btnStrLeft, String btnStr, bool visible, Function onTapLeft, Function onTap) {
    return Visibility(
        visible: visible,
        child: Container(
            // height: _isShowCallView() ? 100.w : 260.w,
            alignment: Alignment.bottomCenter,
            child: Row(
              children: [
                Expanded(
                    flex: btnStrLeft != null ? 1 : 0,
                    child: GestureDetector(
                        behavior: HitTestBehavior.opaque,
                        onTap: () {
                          onTapLeft();
                        },
                        child: Container(
                          height: 40.w,
                          width: btnStrLeft != null ? double.infinity : 0,
                          margin: EdgeInsets.only(bottom: 20.w),
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(20.w),
                              border: Border.all(color: ColorRes.colorffb507, width: 1.w)),
                          child: Text(btnStrLeft ?? '',
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                color: ColorRes.colorffb507,
                                fontSize: 16.sp,
                              )),
                        ))),
                Visibility(visible: btnStrLeft != null, child: SizedBox(width: 24.w)),
                Expanded(
                    child: GestureDetector(
                        behavior: HitTestBehavior.opaque,
                        onTap: () {
                          onTap();
                        },
                        child: Container(
                          height: 40.w,
                          alignment: Alignment.center,
                          margin: EdgeInsets.only(bottom: 20.w),
                          decoration:
                              BoxDecoration(borderRadius: BorderRadius.circular(20.w), color: ColorRes.colorffb507),
                          child: Text(btnStr,
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                color: ColorRes.white,
                                fontSize: 16.sp,
                              )),
                        )))
              ],
            )));
  }

  String? _getAlertMsg() {
    if (_isProceedConsultation()) {
      if (ConsultationUtils.isPhoneConsult(_consultModel?.type)) {
        return '提示：为了保障您的个人信息安全，您的电话号码将被隐私保护，患者端看到的是中间号码，通话全程免费。';
      }
    } else if (_isNoConsultation()) {
      return '请及时处理问诊，超过24小时未处理问诊，平台将自动退诊。';
    }
    return null;
  }

  /// 展示拒绝原因弹窗
  _buildRefuseDialog(List<DictModel> list) {
    list[0].isSelect = true;
    return CommWidget.buildBottomSheetDialog(context,
        title: '暂不接诊',
        isPadding: false,
        buildView: (c) => Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: list
                  .map<Widget>((e) => GestureDetector(
                        behavior: HitTestBehavior.opaque,
                        onTap: () {
                          for (var element in list) {
                            element.isSelect = false;
                          }
                          e.isSelect = true;
                          (c as Element).markNeedsBuild();
                        },
                        child: Container(
                          height: 40.w,
                          margin: EdgeInsets.only(left: 24.w, right: 24.w),
                          child: Row(
                            children: [
                              ImageLoader.loadAsset(e.isSelect ? 'icon_bank_select.webp' : 'icon_unselected.webp', 15.w),
                              SizedBox(width: 15.w),
                              Text(e.name ?? '',
                                  textAlign: TextAlign.left,
                                  style: TextStyle(
                                    color: ColorRes.color333333,
                                    fontSize: 14.sp,
                                  ))
                            ],
                          ),
                        ),
                      ))
                  .toList()
                ..add(CommWidget.buildLine())
                ..add(Container(
                  margin: EdgeInsets.only(top: 10.w, right: 16.w, left: 16.w),
                  child: Row(
                    children: [
                      Expanded(
                          child: CommWidget.buildLeftBtn('取消', () {
                        c.pop();
                      })),
                      SizedBox(width: 30.w),
                      Expanded(
                          child: CommWidget.buildRightBtn('确认', () {
                        c.pop();
                        var feedBack = list.firstWhereOrNull((element) => element.isSelect)?.name ?? '';
                        _refuseImageTextConsultation(_consultModel?.id ?? '', feedBack);
                      })),
                    ],
                  ),
                )),
            ));
  }

  /// 修改虚拟手机号
  _buildEditPhoneNumberDialog() {
    var textEditingController = TextEditingController();
    showDialog(
        context: context,
        builder: (context) {
          return Dialog(
              child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              SizedBox(height: 22.w),
              Text('修改接听电话',
                  style: TextStyle(color: ColorRes.color333333, fontSize: 17.sp, fontWeight: FontWeight.bold)),
              SizedBox(height: 22.w),
              Container(
                  margin: EdgeInsets.only(right: 15.w, left: 15.w),
                  padding: EdgeInsets.all(5.w),
                  height: 50.w,
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                      border: Border.all(
                        width: 1.w,
                        color: ColorRes.colordddddd,
                      ),
                      borderRadius: BorderRadius.circular(5.w)),
                  child: TextField(
                    controller: textEditingController,
                    decoration: const InputDecoration(
                      hintText: '请输入电话号码...',
                      border: InputBorder.none,
                    ),
                  )),
              Container(
                margin: EdgeInsets.only(left: 15.w, right: 15.w, top: 15.w),
                child: Text('注：本次修改是临时修改，修改号码后，请使用新号码的手机或座机拨打电话。固定电话格式：区号+电话号码，区号不含首位0。',
                    style: TextStyle(color: ColorRes.color666666, fontSize: 16.sp)),
              ),
              SizedBox(height: 20.w),
              Container(color: ColorRes.colorEEF2F5, height: 1),
              SizedBox(
                height: 50.w,
                width: double.infinity,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Expanded(
                      child: GestureDetector(
                          behavior: HitTestBehavior.opaque,
                          onTap: () {
                            context.pop([0, '']);
                          },
                          child: Text('取消',
                              textAlign: TextAlign.center,
                              style: TextStyle(color: ColorRes.color666666, fontSize: 17.sp))),
                    ),
                    Container(
                      width: 1,
                      color: ColorRes.colorEEF2F5,
                    ),
                    Expanded(
                      child: GestureDetector(
                          behavior: HitTestBehavior.opaque,
                          onTap: () {
                            var string = textEditingController.text.trim().toString();
                            if (StringUtils.isEmpty(string)) {
                              Fluttertoast.showToast(msg: '请输入电话号码');
                              return;
                            }
                            context.pop([1, string]);
                          },
                          child: Text('确定',
                              textAlign: TextAlign.center,
                              style: TextStyle(color: ColorRes.color518DF6, fontSize: 17.sp))),
                    )
                  ],
                ),
              )
            ],
          ));
        }).then((value) {
      if (value != null) {
        var v1 = value[0];
        if (v1 != 0) {
          var v2 = value[1];
          _updateDoctorCall(v2);
        }
      }
    });
  }

  @override
  void dispose() {
    // 组件销毁时判断Timer是否仍然处于激活状态，是则取消
    if (_timer?.isActive == true) {
      _timer?.cancel();
    }
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  /// 诊疗中
  bool _isProceedConsultation() {
    return _consultModel?.status == '3';
  }

  /// 未接诊
  bool _isNoConsultation() {
    return _consultModel?.status == '0' || _consultModel?.status == '1';
  }

  /// 完成处理
  bool _isCoverConsultation() {
    var status = _consultModel?.status;
    return status == '2' || status == '4' || status == '5' || status == '6';
  }

  /// 是否展示查看历史记录按钮
  bool _isShowMsgHistory() {
    var status = _consultModel?.status;
    return status == '4' || status == '5' || status == '6';
  }

  /// 启动Timer
  _startTimer() {
    if (_isNoConsultation() || _isProceedConsultation()) {
      cancelTimer();
      _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
        var time = MyDateUtils.stringToInt(_consultModel?.endTime) - DateTime.now().millisecondsSinceEpoch;
        _timeRemaining = MyDateUtils.countDown(time);
        setState(() {});
      });
    } else {
      _timeRemaining = MyDateUtils.countDown((_consultModel?.consultLength ?? 0) * 1000);
      setState(() {});
    }
  }

  /// 结束timer
  cancelTimer() {
    if (_timer != null) {
      _timer?.cancel();
    }
  }

  /// 咨询详情
  _findConsultDetail() async {
    status = 1;
    var response = await HttpClient.postJson(HttpRequest(Api.findConsultDetail, body: {
      'id': widget.consultId,
    }));
    var serviceResult = ServiceResult<ConsultModel>(response, (map) => ConsultModel.fromJson(map));

    if (serviceResult.success) {
      _setConsultModel(serviceResult.responseBody);
    }
  }

  _setConsultModel(ConsultModel? consultModel) {
    _consultModel = consultModel;
    _imgArr = _consultModel?.illInfo?.split('|').toList() ?? [];
    //倒计时
    _startTimer();
    setState(() {});
  }

  /// 拒绝原因字典数据
  _getRefuseList() async {
    var response = await HttpClient.get(HttpRequest(Api.getByDict, urlParams: {'dictType': 'refuse_consult_type'}));
    var serviceResult = ServiceResult<List<DictModel>>.list(
        response, (list) => (list ?? []).map((e) => DictModel.fromJson(e)).toList());
    if (serviceResult.success) {
      var responseBody = serviceResult.responseBody;
      if (responseBody == null || responseBody.isEmpty) return;
      _buildRefuseDialog(responseBody);
    }
  }

  /// 拒绝接诊
  _refuseImageTextConsultation(String id, String endFeedBack) async {
    var response = await HttpClient.post(HttpRequest(Api.refuseConsult, body: {'id': id, 'endFeekBack': endFeedBack}));
    var serviceResult = ServiceResult.simple(response);
    if (serviceResult.success) {
      Fluttertoast.showToast(msg: '操作成功');
      if (!mounted) return;
      CommWidget.pop(context);
    } else {
      Fluttertoast.showToast(msg: '操作失败，请稍后再试');
    }
  }

  /// 接诊
  _handlerConsultation() async {
    var response = await HttpClient.post(HttpRequest(Api.handConsult, body: {'id': _consultModel?.id}));
    var serviceResult = ServiceResult<ConsultModel>(response, (map) => ConsultModel.fromJson(map));
    if (serviceResult.success) {
      _consultModel = serviceResult.responseBody;
      setState(() {});
    } else {
      Fluttertoast.showToast(msg: serviceResult.responseMsg ?? '服务器打盹了，请稍后再试！');
    }
  }

  bool _isShowCallView() {
    return (ConsultationUtils.isPhoneConsult(_consultModel?.type) ||
            ConsultationUtils.isVideoConsult(_consultModel?.type)) &&
        _isProceedConsultation();
  }

  String _getReasonStr() {
    var str = _consultModel?.endFeedback ?? '';
    if (_consultModel?.status == '4' || _consultModel?.status == '6') {
      str = _consultModel?.refuseConsult ?? '';
    }
    return str;
  }

  String _getReasonTitleStr() {
    var str = '原因：';
    if (_consultModel?.status == '4' || _consultModel?.status == '6') {
      str = '未接诊原因：';
    }
    return str;
  }

  String? _getRefundStr() {
    String? str;
    switch (_consultModel?.refund ?? '') {
      case '0':
        str = '未退费';
        if (_consultModel?.status == '2') {
          str = null;
        }
        break;
      case '1':
        str = '已退费';
        break;
      case '2':
        str = '退费失败';
        break;
    }
    return str;
  }

  String _getStatusImage() {
    var image = 'icon_consult_info_end.webp';
    var status = _consultModel?.status;
    if (status == '2') {
      if (_consultModel?.refund == '0') {
        image = 'icon_consult_info_end.webp';
      } else if (_consultModel?.refund == '1') {
        image = 'icon_consult_info_not_end.webp';
      } else if (_consultModel?.refund == '2') {
        image = 'icon_consult_info_not_end.webp';
      }
    } else if (status == '4') {
      image = 'icon_consult_info_time_out.webp';
    } else if (status == '5' || status == '6') {
      image = 'icon_consult_info_aidl.webp';
    }
    return image;
  }

  /// 电话呼叫
  _phoneCall() async {
    var response = await HttpClient.post(HttpRequest(Api.findAnonymousCall, body: {'id': _consultModel?.id}));
    var serviceResult = ServiceResult.simple(response);
    if (serviceResult.success) {
      var phone = serviceResult.responseBody;
      if (StringUtils.isNotEmpty(phone)) {
        NativeInterface().call(phone);
      } else {
        Fluttertoast.showToast(msg: '未获取到患者电话');
      }
      return;
    }
    serviceResult.toastErrorMsg();
  }

  /// 视频呼叫
  _videoCall() {
    NativeInterface().openNativePage('video_call', jsonEncode(_consultModel?.toJson()));
  }

  /// 图文咨询
  _startImageTextConsultation() {
    NativeInterface().openNativePage('image_text_consultation', jsonEncode(_consultModel?.toJson()));
  }

  /// 修改医生的匿名手机号
  _updateDoctorCall(String phone) async {
    var response =
        await HttpClient.post(HttpRequest(Api.updateDoctorCall, body: {'id': _consultModel?.id, 'phone': phone}));
    var serviceResult = ServiceResult.simple(response);
    if (serviceResult.success) {
      _phoneStr = phone;
      setState(() {});
    }
  }
}
